package mapper

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"ksd-social-api/modules/note/model"
)

type AdminNoteCategoryMapper struct{}

/**
 * 查找小册分类
 * @author feige
 * @date 2023-11-03
 * @version 1.0
 * @desc
 */
func (mapper *AdminNoteCategoryMapper) FindCategoriesAll(systemId uint64) ([]model.NoteCategory, error) {
	// 获取数据库链接
	mysql := orm.NewOrm()
	// 准备一个切片容器
	var categorys []model.NoteCategory
	// 执行查询
	_, err := mysql.Raw("select id,title,icon,parent_id from xk_note_category where is_deleted = 0 and system_id = ? order by sorted ").SetArgs(systemId).QueryRows(&categorys)
	if err != nil {
		return nil, err
	}
	return categorys, nil
}

/**
 * 查找小册分类
 * @author feige
 * @date 2023-11-03
 * @version 1.0
 * @desc
 */
func (mapper *AdminNoteCategoryMapper) FindCategoriesAllAdmin(status int64, channelId uint64, systemId uint64) ([]model.NoteCategory, error) {
	// 获取数据库链接
	mysql := orm.NewOrm()
	// 准备一个切片容器
	var categorys []model.NoteCategory
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_note_category")
	// 4: 设定两个条件
	cond = cond.
		And("system_id", systemId).
		And("is_deleted", 0)
	if status > -1 {
		cond = cond.And("status", status)
	}
	if channelId > 0 {
		cond = cond.And("channel_id", channelId)
	}

	querySeter := qs.SetCond(cond)
	querySeter = querySeter.OrderBy("sorted")
	_, err := querySeter.All(&categorys)
	if err != nil {
		return nil, err
	}
	return categorys, nil
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (mapper *AdminNoteCategoryMapper) UpdateFieldById(id uint64, field string, value any, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw(fmt.Sprintf("update xk_note_category set %s='%v',update_time=now() where id = ? and system_id = ?", field, value)).SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminNoteCategoryMapper) DelById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_note_category  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存和修改兑换码
 */
func (service *AdminNoteCategoryMapper) SaveUpdateCategory(category model.NoteCategory) *model.NoteCategory {
	db := orm.NewOrm()
	if category.Id > 0 {
		_, _ = db.Update(&category)
		return &category
	} else {
		_, _ = db.Insert(&category)
		return &category
	}
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询小册信息
 */
func (mapper *AdminNoteCategoryMapper) GetById(id uint64, systemId uint64) *model.NoteCategory {
	// 1: 创建一个数据连接
	db := orm.NewOrm()
	// 2: 赋予id给结构体
	dbNote := model.NoteCategory{Id: id, SystemId: systemId}
	// 3: 读取id的数据放入到结构体，进行返回
	_ = db.Read(&dbNote, "id", "system_id")
	// 4: 结构返回
	return &dbNote
}
